import React, { useEffect, useState } from 'react'

import Notification, { Color, NotificatonProps } from './Notification'

interface Props {
	setNotify(fn: (params: NotificatonProps) => void): void
}
interface NoteInterface {
	id: number
	autoClose?: boolean
	color?: string
	typeText?: string
	timeDelly?: number
}
function NotificationsManager(props: Props) {
	const { setNotify } = props
	const [notifications, setNotifications] = useState<NoteInterface[]>([])

	const createNotification = (
		autoClose: any,
		children: any,
		color?: string,
		typeText?: string,
		timeDelly?: number
	) => {
		setNotifications((prevNotifications) => [
			...prevNotifications,
			{
				children,
				autoClose,
				color,
				typeText,
				timeDelly,
				id: prevNotifications.length,
			},
		])
	}

	useEffect(() => {
		setNotify(({ autoClose, children, color, typeText, timeDelly }) =>
			createNotification(autoClose, children, color, typeText, timeDelly)
		)
	}, [setNotify])

	const deleteNotification = (id: number): void => {
		const filteredNotifications = notifications.filter((_, index) => id !== index, [])
		setNotifications(filteredNotifications)
	}

	
	return (
		<template>
			 {/* 
			 map中item结构出来
			 arr.map(item,index)
			 arr.map({ id, ...props}, index)

			 组件 
			 <Notification key={id} onDelete={(): void => deleteNotification(index)} {...props} />
			 直接使用id
			 {...props} 将item中剩余的属性传递过去
			 */}
			{notifications.map(({ id, ...props }, index) => (
				<Notification key={id} onDelete={(): void => deleteNotification(index)} {...props} />
			))}
		</template>
	)
}

export default NotificationsManager
